package org.apache.lucene.index;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Cache based on bytes used
 * 
 */
// TODO: needs synchronization
// TODO: needs to be multiversioned
public class TagBlockLRUCache {
  private LinkedHashMap<TagBlockKey,TagBlockWriter> map;
  private int maxSize;

  public TagBlockLRUCache(int maxSize) {
    this.maxSize = maxSize;
    map = new LinkedHashMap<TagBlockKey,TagBlockWriter>(16, 0.75f, true); // use access order for removeOverSized
  }

  public void put(Term term, int blockNum, TagBlockWriter tagBlockWriter) {
    int size = tagBlockWriter.getDocsSize() + tagBlockWriter.getSkipSize();
    removeOverSized();
  }

  private void removeOverSized() {
    Iterator<Map.Entry<TagBlockKey,TagBlockWriter>> iterator = map.entrySet().iterator();
    int csize = 0;
    while (iterator.hasNext()) {
      Map.Entry<TagBlockKey,TagBlockWriter> entry = iterator.next();
      TagBlockWriter tbw = entry.getValue();
      int size = tbw.getDocsSize() + tbw.getSkipSize();
      csize += size;
      if (csize > maxSize) {
        iterator.remove(); // remove entries that go over maxsize
      }
    }
  }

  public TagBlockWriter get(Term term, int blockNum) {
    TagBlockKey key = new TagBlockKey(blockNum, term);
    return map.get(key);
  }
}
